import type { Next, Context } from 'koa';
import { prefix } from '../routes';

/**
 * 启动引导(扩展Koa)
 * @param ctx
 * @param next
 */
export default async function (ctx: Context, next: Next) {
    const [controller, action] = ctx.path
        .replace(prefix, '')
        .split('/')
        .filter((s) => s.length);
    ctx.controller = controller;
    ctx.action = action;
    ctx.success = function (data: any, message?: string) {
        ctx.state.data = data;
        ctx.state.errmsg = message || 'success';
    };
    ctx.fail = function (errno: number, errmsg?: string) {
        ctx.state.errno = errno;
        ctx.state.errmsg = errmsg || 'fail';
    };
    ctx.end = function () {
        throw new Error('ctx end');
    };
    return next();
}
